﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/* ############################################################################################
 *           Matthijs Hilgers - Gerben Boot - Marcel Boelen - Joep van den Hoven
 *               1580499          1575754        1582702            1592146         
 * ############################################################################################
 * 
 *  Date     || Changed                                  || By              || Source
 *  ===========================================================================================
 *  28-03-12 || First version                            || Gerben          || new
 */  

namespace MultipleOutputNeuralNetwork {
    class Node {
        private double threshold;
        public int value = 0;
        private List<NodeConnection> inputConnections;

        public Node() {
            threshold = Math.Round(new Random().NextDouble() * 10, 2);
            inputConnections = new List<NodeConnection>();
        }

        public Node(double threshold) {
            this.threshold = threshold;
            inputConnections = new List<NodeConnection>();
        }

        public void addInputConnection(NodeConnection nodeConnection) {
            inputConnections.Add(nodeConnection);
        }

        public void run() {
            double value = 0;
            foreach (NodeConnection inputConnection in inputConnections) {
                value += inputConnection.node.value * inputConnection.weight;
            }
            this.value = value >= threshold ? 1 : 0;
        }

        public void setValue(int value) {
            this.value = value;
        }

        public Boolean learn(int newOutput) {
            double inputValue = 0;
            foreach (NodeConnection inputConnection in inputConnections) {
                inputValue += inputConnection.node.value * inputConnection.weight;
            }
            int output = inputValue >= threshold ? 1 : 0;
            value = output;
            if (output != newOutput) {
                int i =0; 
                foreach(NodeConnection inputConnection in inputConnections)
                    i += inputConnection.node.value;
                double changeValue = (threshold - inputValue) / i;
                changeValue = changeValue > 0 ? changeValue + 0.01 : changeValue - 0.01;

                if (changeValue == 0.0)
                    changeValue -= 0.0000001;

                foreach (NodeConnection inputConnection in inputConnections)
                    inputConnection.weight += inputConnection.node.value * changeValue;
                return true;
            }
            return false;
        }
    }
}
